<template>
  <div class="designer-container">
    <!-- 工具箱 -->
    <div class="toolbox">
      <h3>组件工具箱</h3>
      <el-collapse v-model="activeCategories">
        <el-collapse-item v-for="category in componentCategories" :key="category.name" :title="category.label" :name="category.name">
          <div class="component-list">
            <el-card 
              v-for="comp in category.components" 
              :key="comp.name"
              class="component-item"
              shadow="hover"
              draggable="true"
              @dragstart="dragStart($event, comp)"
            >
              <div class="component-label">{{ comp.label }}</div>
              <div class="component-icon">
                <el-icon>
                  <component :is="comp.icon" />
                </el-icon>
              </div>
            </el-card>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 画板 -->
    <div class="canvas" 
         @drop="drop($event)" 
         @dragover.prevent
         @mousedown="handleCanvasMouseDown"
         @mousemove="handleCanvasMouseMove"
         @mouseup="handleCanvasMouseUp"
         @mouseleave="handleCanvasMouseUp"
         @wheel="handleCanvasWheel"
         @click="clearSelection">
      <div class="canvas-controls">
        <el-button-group>
          <el-button size="small" @click="zoomCanvas(0.1)" title="放大">
            <el-icon><Plus /></el-icon>
          </el-button>
          <el-button size="small" @click="zoomCanvas(-0.1)" title="缩小">
            <el-icon><Minus /></el-icon>
          </el-button>
          <el-button size="small" @click="resetCanvas" title="重置">
            <el-icon><Refresh /></el-icon>
          </el-button>
          <el-button size="small" @click="undo" title="撤销 (Ctrl+Z)">
            <el-icon><RefreshLeft /></el-icon>
          </el-button>
          <el-button size="small" @click="redo" title="重做 (Ctrl+Y)">
            <el-icon><RefreshRight /></el-icon>
          </el-button>
        </el-button-group>
        <span class="zoom-level">缩放: {{ Math.round(canvasState.transform.scale * 100) }}%</span>
      </div>
      <div class="canvas-content" 
           :style="{
             transform: `translate(${canvasState.transform.x}px, ${canvasState.transform.y}px) scale(${canvasState.transform.scale})`,
             transformOrigin: '0 0'
           }">
                  <UniversalComponentWrapper
                    v-for="(item, index) in canvasItems"
                    :key="index"
                    :component="item.component"
                    :props="item.props"
                    :children="item.children || []"
                    @selected="selectItem(index)"
                    @update:children="(newChildren) => updateChildren(index, newChildren)"
                    @childSelected="(childIndex) => selectNestedItem(index, childIndex)"
                  />
        <div v-if="canvasItems.length === 0" class="empty-canvas">
          将组件拖放到此处
        </div>
      </div>
    </div>

    <!-- 属性面板 -->
    <div class="property-panel">
      <h3>属性配置</h3>
      <el-empty v-if="selectedItem === null" description="请选择一个组件" />
      <el-form v-else label-position="top">
        <!-- 处理普通组件 -->
        <template v-if="typeof selectedItem === 'number'">
          <el-form-item label="组件类型">
            <el-tag>{{ canvasItems[selectedItem].component }}</el-tag>
          </el-form-item>
          
          <!-- 组件属性分类 -->
          <el-tabs>
            <el-tab-pane label="基础属性">
              <el-form-item 
                v-for="(propValue, propKey) in getBasicProps(canvasItems[selectedItem].props)" 
                :key="propKey"
                :label="getPropLabel(propKey)"
              >
                <!-- 根据属性类型渲染不同的编辑器 -->
                <template v-if="typeof propValue === 'string'">
                  <!-- 特殊字符串属性处理 -->
                  <template v-if="isColorProp(propKey)">
                    <el-color-picker v-model="canvasItems[selectedItem].props[propKey]" show-alpha />
                  </template>
                  <template v-else-if="isSelectProp(propKey)">
                    <el-select v-model="canvasItems[selectedItem].props[propKey]" style="width: 100%">
                      <el-option 
                        v-for="option in getSelectOptions(propKey, canvasItems[selectedItem].component)" 
                        :key="option.value" 
                        :label="option.label" 
                        :value="option.value" 
                      />
                    </el-select>
                  </template>
                  <template v-else>
                    <el-input v-model="canvasItems[selectedItem].props[propKey]" />
                  </template>
                </template>
                <template v-else-if="typeof propValue === 'boolean'">
                  <el-switch v-model="canvasItems[selectedItem].props[propKey]" />
                </template>
                <template v-else-if="typeof propValue === 'number'">
                  <el-input-number v-model="canvasItems[selectedItem].props[propKey]" style="width: 100%" />
                </template>
                <template v-else-if="Array.isArray(propValue)">
                  <el-tag 
                    v-for="(item, index) in propValue" 
                    :key="index" 
                    closable 
                    @close="removeArrayItem(selectedItem, propKey, index)"
                    style="margin-right: 5px; margin-bottom: 5px;"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    v-model="newArrayItem"
                    placeholder="添加新项"
                    size="small"
                    style="width: 100%; margin-top: 5px;"
                    @keyup.enter="addArrayItem(selectedItem, propKey)"
                  >
                    <template #append>
                      <el-button @click="addArrayItem(selectedItem, propKey)">添加</el-button>
                    </template>
                  </el-input>
                </template>
                <template v-else-if="typeof propValue === 'object' && propValue !== null && !Array.isArray(propValue)">
                  <el-collapse>
                    <el-collapse-item :title="propKey">
                      <el-form-item 
                        v-for="(nestedValue, nestedKey) in propValue" 
                        :key="nestedKey"
                        :label="getPropLabel(nestedKey)"
                      >
                        <template v-if="typeof nestedValue === 'string'">
                          <template v-if="isColorProp(nestedKey)">
                            <el-color-picker v-model="canvasItems[selectedItem].props[propKey][nestedKey]" show-alpha />
                          </template>
                          <template v-else>
                            <el-input v-model="canvasItems[selectedItem].props[propKey][nestedKey]" />
                          </template>
                        </template>
                        <template v-else-if="typeof nestedValue === 'boolean'">
                          <el-switch v-model="canvasItems[selectedItem].props[propKey][nestedKey]" />
                        </template>
                        <template v-else-if="typeof nestedValue === 'number'">
                          <el-input-number v-model="canvasItems[selectedItem].props[propKey][nestedKey]" style="width: 100%" />
                        </template>
                      </el-form-item>
                    </el-collapse-item>
                  </el-collapse>
                </template>
                <template v-else>
                  <el-input v-model="canvasItems[selectedItem].props[propKey]" type="textarea" />
                </template>
              </el-form-item>
            </el-tab-pane>
            
            <el-tab-pane label="样式">
              <el-collapse>
                <el-collapse-item title="尺寸与位置">
                  <el-form-item label="宽度">
                                          <el-input v-model="getStyleProp(selectedItem, 'width').value" placeholder="例如: 100px, 50%, auto" />
                  </el-form-item>
                  <el-form-item label="高度">
                                          <el-input v-model="getStyleProp(selectedItem, 'height').value" placeholder="例如: 100px, auto" />
                  </el-form-item>
                  <el-form-item label="最小宽度">
                    <el-input v-model="getStyleProp(selectedItem, 'minWidth').value" placeholder="例如: 100px" />
                  </el-form-item>
                  <el-form-item label="最小高度">
                    <el-input v-model="getStyleProp(selectedItem, 'minHeight').value" placeholder="例如: 100px" />
                  </el-form-item>
                </el-collapse-item>
                
                <el-collapse-item title="边距">
                  <el-form-item label="外边距">
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'marginTop').value" placeholder="上" />
                      </el-col>
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'marginRight').value" placeholder="右" />
                      </el-col>
                    </el-row>
                    <el-row :gutter="10" style="margin-top: 10px;">
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'marginBottom').value" placeholder="下" />
                      </el-col>
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'marginLeft').value" placeholder="左" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                  
                  <el-form-item label="内边距">
                    <el-row :gutter="10">
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'paddingTop').value" placeholder="上" />
                      </el-col>
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'paddingRight').value" placeholder="右" />
                      </el-col>
                    </el-row>
                    <el-row :gutter="10" style="margin-top: 10px;">
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'paddingBottom').value" placeholder="下" />
                      </el-col>
                      <el-col :span="12">
                        <el-input v-model="getStyleProp(selectedItem, 'paddingLeft').value" placeholder="左" />
                      </el-col>
                    </el-row>
                  </el-form-item>
                </el-collapse-item>
                
                <el-collapse-item title="边框">
                  <el-form-item label="边框样式">
                    <el-select v-model="getStyleProp(selectedItem, 'borderStyle').value" style="width: 100%">
                      <el-option label="无" value="none" />
                      <el-option label="实线" value="solid" />
                      <el-option label="虚线" value="dashed" />
                      <el-option label="点线" value="dotted" />
                      <el-option label="双线" value="double" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="边框宽度">
                    <el-input v-model="getStyleProp(selectedItem, 'borderWidth').value" placeholder="例如: 1px" />
                  </el-form-item>
                  
                  <el-form-item label="边框颜色">
                    <el-color-picker v-model="getStyleProp(selectedItem, 'borderColor').value" show-alpha />
                  </el-form-item>
                  
                  <el-form-item label="边框圆角">
                    <el-input v-model="getStyleProp(selectedItem, 'borderRadius').value" placeholder="例如: 4px" />
                  </el-form-item>
                </el-collapse-item>
                
                <el-collapse-item title="背景">
                  <el-form-item label="背景类型">
                    <el-select v-model="getStyleProp(selectedItem, 'backgroundType').value" style="width: 100%">
                      <el-option label="纯色" value="solid" />
                      <el-option label="线性渐变" value="linear-gradient" />
                      <el-option label="径向渐变" value="radial-gradient" />
                      <el-option label="图片" value="image" />
                    </el-select>
                  </el-form-item>
                  
                  <template v-if="getStyleProp(selectedItem, 'backgroundType').value === 'solid'">
                    <el-form-item label="背景颜色">
                      <el-color-picker v-model="getStyleProp(selectedItem, 'backgroundColor').value" show-alpha />
                    </el-form-item>
                  </template>
                  
                  <template v-if="getStyleProp(selectedItem, 'backgroundType').value === 'linear-gradient'">
                    <el-form-item label="渐变方向">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundGradientDirection').value" placeholder="例如: to right" />
                    </el-form-item>
                    <el-form-item label="渐变颜色">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundGradientColors').value" placeholder="例如: red, blue" />
                    </el-form-item>
                  </template>
                  
                  <template v-if="getStyleProp(selectedItem, 'backgroundType').value === 'radial-gradient'">
                    <el-form-item label="渐变形状">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundGradientShape').value" placeholder="例如: circle" />
                    </el-form-item>
                    <el-form-item label="渐变位置">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundGradientPosition').value" placeholder="例如: center" />
                    </el-form-item>
                    <el-form-item label="渐变颜色">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundGradientColors').value" placeholder="例如: red, blue" />
                    </el-form-item>
                  </template>
                  
                  <template v-if="getStyleProp(selectedItem, 'backgroundType').value === 'image'">
                    <el-form-item label="背景图片URL">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundImage').value" placeholder="输入图片URL" />
                    </el-form-item>
                    <el-form-item label="背景大小">
                      <el-select v-model="getStyleProp(selectedItem, 'backgroundSize').value" style="width: 100%">
                        <el-option label="自动" value="auto" />
                        <el-option label="覆盖" value="cover" />
                        <el-option label="包含" value="contain" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="背景重复">
                      <el-select v-model="getStyleProp(selectedItem, 'backgroundRepeat').value" style="width: 100%">
                        <el-option label="重复" value="repeat" />
                        <el-option label="不重复" value="no-repeat" />
                        <el-option label="水平重复" value="repeat-x" />
                        <el-option label="垂直重复" value="repeat-y" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="背景位置">
                      <el-input v-model="getStyleProp(selectedItem, 'backgroundPosition').value" placeholder="例如: center top" />
                    </el-form-item>
                  </template>
                  
                  <el-form-item label="背景附着">
                    <el-select v-model="getStyleProp(selectedItem, 'backgroundAttachment').value" style="width: 100%">
                      <el-option label="滚动" value="scroll" />
                      <el-option label="固定" value="fixed" />
                      <el-option label="局部" value="local" />
                    </el-select>
                  </el-form-item>
                </el-collapse-item>
                
                <el-collapse-item title="文本">
                  <el-form-item label="文本颜色">
                    <el-color-picker v-model="getStyleProp(selectedItem, 'color').value" />
                  </el-form-item>
                  
                  <el-form-item label="字体大小">
                    <el-input v-model="getStyleProp(selectedItem, 'fontSize').value" placeholder="例如: 14px" />
                  </el-form-item>
                  
                  <el-form-item label="字体粗细">
                    <el-select v-model="getStyleProp(selectedItem, 'fontWeight').value" style="width: 100%">
                      <el-option label="正常" value="normal" />
                      <el-option label="粗体" value="bold" />
                      <el-option label="细体" value="lighter" />
                      <el-option label="100" value="100" />
                      <el-option label="200" value="200" />
                      <el-option label="300" value="300" />
                      <el-option label="400" value="400" />
                      <el-option label="500" value="500" />
                      <el-option label="600" value="600" />
                      <el-option label="700" value="700" />
                      <el-option label="800" value="800" />
                      <el-option label="900" value="900" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="文本对齐">
                    <el-select v-model="getStyleProp(selectedItem, 'textAlign').value" style="width: 100%">
                      <el-option label="左对齐" value="left" />
                      <el-option label="居中" value="center" />
                      <el-option label="右对齐" value="right" />
                      <el-option label="两端对齐" value="justify" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="行高">
                    <el-input v-model="getStyleProp(selectedItem, 'lineHeight').value" placeholder="例如: 1.5 或 24px" />
                  </el-form-item>
                  
                  <el-form-item label="字间距">
                    <el-input v-model="getStyleProp(selectedItem, 'letterSpacing').value" placeholder="例如: 1px" />
                  </el-form-item>
                  
                  <el-form-item label="文本装饰">
                    <el-select v-model="getStyleProp(selectedItem, 'textDecoration').value" style="width: 100%">
                      <el-option label="无" value="none" />
                      <el-option label="下划线" value="underline" />
                      <el-option label="删除线" value="line-through" />
                      <el-option label="上划线" value="overline" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="文本转换">
                    <el-select v-model="getStyleProp(selectedItem, 'textTransform').value" style="width: 100%">
                      <el-option label="无" value="none" />
                      <el-option label="大写" value="uppercase" />
                      <el-option label="小写" value="lowercase" />
                      <el-option label="首字母大写" value="capitalize" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="文本溢出">
                    <el-select v-model="getStyleProp(selectedItem, 'textOverflow').value" style="width: 100%">
                      <el-option label="裁剪" value="clip" />
                      <el-option label="省略号" value="ellipsis" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="空白处理">
                    <el-select v-model="getStyleProp(selectedItem, 'whiteSpace').value" style="width: 100%">
                      <el-option label="正常" value="normal" />
                      <el-option label="不换行" value="nowrap" />
                      <el-option label="保留空格" value="pre" />
                      <el-option label="保留空格换行" value="pre-wrap" />
                      <el-option label="保留空格不换行" value="pre-line" />
                    </el-select>
                  </el-form-item>
                </el-collapse-item>
                
                <el-collapse-item title="Flex布局">
                  <el-form-item label="显示方式">
                    <el-select v-model="getStyleProp(selectedItem, 'display').value" style="width: 100%">
                      <el-option label="块级元素" value="block" />
                      <el-option label="行内元素" value="inline" />
                      <el-option label="行内块元素" value="inline-block" />
                      <el-option label="Flex布局" value="flex" />
                      <el-option label="Grid布局" value="grid" />
                    </el-select>
                  </el-form-item>
                  
                  <template v-if="getStyleProp(selectedItem, 'display').value === 'flex'">
                    <el-form-item label="主轴方向">
                      <el-select v-model="getStyleProp(selectedItem, 'flexDirection').value" style="width: 100%">
                        <el-option label="水平方向" value="row" />
                        <el-option label="水平反向" value="row-reverse" />
                        <el-option label="垂直方向" value="column" />
                        <el-option label="垂直反向" value="column-reverse" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="主轴对齐">
                      <el-select v-model="getStyleProp(selectedItem, 'justifyContent').value" style="width: 100%">
                        <el-option label="起点对齐" value="flex-start" />
                        <el-option label="终点对齐" value="flex-end" />
                        <el-option label="居中对齐" value="center" />
                        <el-option label="两端对齐" value="space-between" />
                        <el-option label="环绕对齐" value="space-around" />
                        <el-option label="均匀对齐" value="space-evenly" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="交叉轴对齐">
                      <el-select v-model="getStyleProp(selectedItem, 'alignItems').value" style="width: 100%">
                        <el-option label="起点对齐" value="flex-start" />
                        <el-option label="终点对齐" value="flex-end" />
                        <el-option label="居中对齐" value="center" />
                        <el-option label="基线对齐" value="baseline" />
                        <el-option label="拉伸对齐" value="stretch" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="换行方式">
                      <el-select v-model="getStyleProp(selectedItem, 'flexWrap').value" style="width: 100%">
                        <el-option label="不换行" value="nowrap" />
                        <el-option label="换行" value="wrap" />
                        <el-option label="反向换行" value="wrap-reverse" />
                      </el-select>
                    </el-form-item>
                    
                    <el-form-item label="Flex子项排序">
                      <el-input-number v-model="getStyleProp(selectedItem, 'order').value" :min="0" :max="10" />
                    </el-form-item>
                    
                    <el-form-item label="Flex子项扩展">
                      <el-input-number v-model="getStyleProp(selectedItem, 'flexGrow').value" :min="0" :max="10" />
                    </el-form-item>
                    
                    <el-form-item label="Flex子项收缩">
                      <el-input-number v-model="getStyleProp(selectedItem, 'flexShrink').value" :min="0" :max="10" />
                    </el-form-item>
                    
                    <el-form-item label="Flex子项基准">
                      <el-input v-model="getStyleProp(selectedItem, 'flexBasis').value" placeholder="例如: 100px, auto" />
                    </el-form-item>
                  </template>
                  
                  <template v-if="getStyleProp(selectedItem, 'display').value === 'grid'">
                    <el-form-item label="网格模板列">
                      <el-input v-model="getStyleProp(selectedItem, 'gridTemplateColumns').value" placeholder="例如: 1fr 1fr 1fr" />
                    </el-form-item>
                    
                    <el-form-item label="网格模板行">
                      <el-input v-model="getStyleProp(selectedItem, 'gridTemplateRows').value" placeholder="例如: 100px 100px" />
                    </el-form-item>
                    
                    <el-form-item label="网格列间距">
                      <el-input v-model="getStyleProp(selectedItem, 'gridColumnGap').value" placeholder="例如: 10px" />
                    </el-form-item>
                    
                    <el-form-item label="网格行间距">
                      <el-input v-model="getStyleProp(selectedItem, 'gridRowGap').value" placeholder="例如: 10px" />
                    </el-form-item>
                    
                    <el-form-item label="网格子项列位置">
                      <el-input v-model="getStyleProp(selectedItem, 'gridColumn').value" placeholder="例如: 1 / 3" />
                    </el-form-item>
                    
                    <el-form-item label="网格子项行位置">
                      <el-input v-model="getStyleProp(selectedItem, 'gridRow').value" placeholder="例如: 1 / 3" />
                    </el-form-item>
                  </template>
                </el-collapse-item>
                
                <el-collapse-item title="过渡与动画">
                  <el-form-item label="过渡属性">
                    <el-input v-model="getStyleProp(selectedItem, 'transitionProperty').value" placeholder="例如: all, opacity" />
                  </el-form-item>
                  
                  <el-form-item label="过渡时间">
                    <el-input v-model="getStyleProp(selectedItem, 'transitionDuration').value" placeholder="例如: 0.3s" />
                  </el-form-item>
                  
                  <el-form-item label="过渡函数">
                    <el-select v-model="getStyleProp(selectedItem, 'transitionTimingFunction').value" style="width: 100%">
                      <el-option label="线性" value="linear" />
                      <el-option label="缓入" value="ease-in" />
                      <el-option label="缓出" value="ease-out" />
                      <el-option label="缓入缓出" value="ease-in-out" />
                      <el-option label="贝塞尔曲线" value="cubic-bezier(0.4, 0, 0.2, 1)" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="过渡延迟">
                    <el-input v-model="getStyleProp(selectedItem, 'transitionDelay').value" placeholder="例如: 0.1s" />
                  </el-form-item>
                  
                  <el-form-item label="动画名称">
                    <el-input v-model="getStyleProp(selectedItem, 'animationName').value" placeholder="例如: fadeIn" />
                  </el-form-item>
                  
                  <el-form-item label="动画时间">
                    <el-input v-model="getStyleProp(selectedItem, 'animationDuration').value" placeholder="例如: 1s" />
                  </el-form-item>
                  
                  <el-form-item label="动画函数">
                    <el-select v-model="getStyleProp(selectedItem, 'animationTimingFunction').value" style="width: 100%">
                      <el-option label="线性" value="linear" />
                      <el-option label="缓入" value="ease-in" />
                      <el-option label="缓出" value="ease-out" />
                      <el-option label="缓入缓出" value="ease-in-out" />
                    </el-select>
                  </el-form-item>
                  
                  <el-form-item label="动画延迟">
                    <el-input v-model="getStyleProp(selectedItem, 'animationDelay').value" placeholder="例如: 0.5s" />
                  </el-form-item>
                  
                  <el-form-item label="动画迭代">
                    <el-input-number v-model="getStyleProp(selectedItem, 'animationIterationCount').value" :min="1" :max="100" />
                  </el-form-item>
                  
                  <el-form-item label="动画方向">
                    <el-select v-model="getStyleProp(selectedItem, 'animationDirection').value" style="width: 100%">
                      <el-option label="正常" value="normal" />
                      <el-option label="反向" value="reverse" />
                      <el-option label="交替" value="alternate" />
                      <el-option label="交替反向" value="alternate-reverse" />
                    </el-select>
                  </el-form-item>
                </el-collapse-item>
                
                <el-collapse-item title="组件属性">
                  <el-form-item label="组件类型">
                    <el-select v-model="selectedItem.componentType" style="width: 100%">
                      <el-option label="按钮" value="el-button" />
                      <el-option label="输入框" value="el-input" />
                      <el-option label="选择器" value="el-select" />
                      <el-option label="开关" value="el-switch" />
                      <el-option label="单选框" value="el-radio" />
                      <el-option label="复选框" value="el-checkbox" />
                    </el-select>
                  </el-form-item>

                  <template v-if="selectedItem.componentType === 'el-button'">
                    <el-form-item label="按钮类型">
                      <el-select v-model="selectedItem.props.type" style="width: 100%">
                        <el-option label="默认" value="" />
                        <el-option label="主要" value="primary" />
                        <el-option label="成功" value="success" />
                        <el-option label="警告" value="warning" />
                        <el-option label="危险" value="danger" />
                        <el-option label="信息" value="info" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="按钮尺寸">
                      <el-select v-model="selectedItem.props.size" style="width: 100%">
                        <el-option label="默认" value="" />
                        <el-option label="大" value="large" />
                        <el-option label="中" value="default" />
                        <el-option label="小" value="small" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="禁用状态">
                      <el-switch v-model="selectedItem.props.disabled" />
                    </el-form-item>
                    <el-form-item label="圆角按钮">
                      <el-switch v-model="selectedItem.props.round" />
                    </el-form-item>
                    <el-form-item label="按钮文本">
                      <el-input v-model="selectedItem.props.text" />
                    </el-form-item>
                  </template>

                  <template v-if="selectedItem.componentType === 'el-input'">
                    <el-form-item label="输入框类型">
                      <el-select v-model="selectedItem.props.type" style="width: 100%">
                        <el-option label="文本" value="text" />
                        <el-option label="密码" value="password" />
                        <el-option label="数字" value="number" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="占位文本">
                      <el-input v-model="selectedItem.props.placeholder" />
                    </el-form-item>
                    <el-form-item label="禁用状态">
                      <el-switch v-model="selectedItem.props.disabled" />
                    </el-form-item>
                    <el-form-item label="可清空">
                      <el-switch v-model="selectedItem.props.clearable" />
                    </el-form-item>
                  </template>
                </el-collapse-item>

                <el-collapse-item title="变换与效果">
                  <el-form-item label="变换">
                    <el-input v-model="getStyleProp(selectedItem, 'transform').value" placeholder="例如: rotate(45deg) scale(1.2)" />
                  </el-form-item>
                  
                  <el-form-item label="变换原点">
                    <el-input v-model="getStyleProp(selectedItem, 'transformOrigin').value" placeholder="例如: center, 50% 50%" />
                  </el-form-item>
                  
                  <el-form-item label="盒子阴影">
                    <el-input v-model="getStyleProp(selectedItem, 'boxShadow').value" placeholder="例如: 2px 2px 10px rgba(0,0,0,0.2)" />
                  </el-form-item>
                  
                  <el-form-item label="文本阴影">
                    <el-input v-model="getStyleProp(selectedItem, 'textShadow').value" placeholder="例如: 1px 1px 2px #000" />
                  </el-form-item>
                  
                  <el-form-item label="滤镜">
                    <el-input v-model="getStyleProp(selectedItem, 'filter').value" placeholder="例如: blur(5px) brightness(0.5)" />
                  </el-form-item>
                  
                  <el-form-item label="不透明度">
                    <el-slider v-model="getStyleProp(selectedItem, 'opacity').value" :min="0" :max="1" :step="0.1" />
                  </el-form-item>
                  
                  <el-form-item label="混合模式">
                    <el-select v-model="getStyleProp(selectedItem, 'mixBlendMode').value" style="width: 100%">
                      <el-option label="正常" value="normal" />
                      <el-option label="叠加" value="multiply" />
                      <el-option label="滤色" value="screen" />
                      <el-option label="叠加" value="overlay" />
                      <el-option label="变暗" value="darken" />
                      <el-option label="变亮" value="lighten" />
                      <el-option label="颜色减淡" value="color-dodge" />
                      <el-option label="颜色加深" value="color-burn" />
                    </el-select>
                  </el-form-item>
                </el-collapse-item>
              </el-collapse>
            </el-tab-pane>
          </el-tabs>
        </template>
        
        <!-- 处理嵌套组件 -->
        <template v-else-if="selectedItem && selectedItem.type === 'nested'">
          <el-form-item label="嵌套组件">
            <el-tag>{{ canvasItems[selectedItem.parentIndex].children[selectedItem.childIndex].component }}</el-tag>
          </el-form-item>
          <el-divider />
          <el-form-item 
            v-for="(propValue, propKey) in canvasItems[selectedItem.parentIndex].children[selectedItem.childIndex].props" 
            :key="propKey"
            :label="propKey"
          >
            <!-- 根据属性类型渲染不同的编辑器 -->
            <template v-if="typeof propValue === 'string'">
              <el-input v-model="canvasItems[selectedItem.parentIndex].children[selectedItem.childIndex].props[propKey]" />
            </template>
            <template v-else-if="typeof propValue === 'boolean'">
              <el-switch v-model="canvasItems[selectedItem.parentIndex].children[selectedItem.childIndex].props[propKey]" />
            </template>
            <template v-else-if="typeof propValue === 'number'">
              <el-input-number v-model="canvasItems[selectedItem.parentIndex].children[selectedItem.childIndex].props[propKey]" />
            </template>
            <template v-else>
              <el-input v-model="canvasItems[selectedItem.parentIndex].children[selectedItem.childIndex].props[propKey]" type="textarea" />
            </template>
          </el-form-item>
        </template>
      </el-form>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, computed, reactive, watch, onMounted, onBeforeUnmount } from 'vue'
import UniversalComponentWrapper from './UniversalComponentWrapper.vue'
import { 
  ElButton, ElForm, ElFormItem, ElInput, ElCard, ElIcon, 
  ElTag, ElDivider, ElSwitch, ElInputNumber, ElEmpty,
  ElCollapse, ElCollapseItem
} from 'element-plus'
      import {
  Grid, Menu, Operation, Document, Plus, Link, Remove, Star,
  Edit, Select, Switch, Check, Sort, Loading, Collection,
  ArrowDown, Warning, BellFilled, Bell, Goods, DocumentCopy,
  Minus, Refresh, RefreshLeft, RefreshRight
} from '@element-plus/icons-vue'

export default defineComponent({
  name: 'Designer',
  components: {
    UniversalComponentWrapper,
    ElButton, ElForm, ElFormItem, ElInput, ElCard, ElIcon,
    ElTag, ElDivider, ElSwitch, ElInputNumber, ElEmpty,
    ElCollapse, ElCollapseItem,
    Grid, Menu, Operation, Document, Plus, Link, Remove, Star,
    Edit, Select, Switch, Check, Sort, Loading, Collection,
    ArrowDown, Warning, BellFilled, Bell, Goods, DocumentCopy,
    Minus, Refresh, RefreshLeft, RefreshRight
  },
  setup() {
    // 默认展开所有分类
    const activeCategories = ref(['container', 'basic', 'form', 'data', 'navigation', 'feedback'])
    
    // 自由操作相关状态
    const freeTransformState = reactive({
      selectedItems: new Set(), // 当前选中的元素索引集合
      isDragging: false, // 是否正在拖动元素
      isResizing: false, // 是否正在调整大小
      isRotating: false, // 是否正在旋转
      dragStartX: 0, // 拖动起始X坐标
      dragStartY: 0, // 拖动起始Y坐标
      transformOrigin: { x: 0, y: 0 }, // 变换原点
      activeHandle: null, // 当前激活的操作手柄
      snapLines: [], // 对齐辅助线
      showGrid: true, // 是否显示网格
      gridSize: 20, // 网格大小
      snapToGrid: true // 是否吸附到网格
    })

    // 按类别组织组件
    const componentCategories = ref([
      {
        name: 'container',
        label: '容器组件',
        components: [
          { 
            name: 'el-container', 
            label: '布局容器', 
            icon: 'Grid',
            props: { 
              direction: 'vertical',
              style: {
                minHeight: '200px',
                width: '100%'
              }
            } 
          },
          { 
            name: 'el-row', 
            label: '行', 
            icon: 'Menu',
            props: { 
              gutter: 20,
              justify: 'start',
              align: 'middle',
              style: {
                minHeight: '100px',
                width: '100%'
              }
            } 
          },
          { 
            name: 'el-col', 
            label: '列', 
            icon: 'Operation',
            props: { 
              span: 12,
              offset: 0,
              push: 0,
              pull: 0,
              xs: 12,
              sm: 12,
              md: 12,
              lg: 12,
              xl: 12,
              style: {
                minHeight: '80px'
              }
            } 
          },
          { 
            name: 'el-card', 
            label: '卡片', 
            icon: 'Document',
            props: { 
              shadow: 'always', 
              header: '卡片标题',
              bodyStyle: {
                padding: '20px'
              }
            } 
          },
          {
            name: 'el-space',
            label: '间距',
            icon: 'Operation',
            props: {
              direction: 'horizontal',
              alignment: 'center',
              size: 'default',
              wrap: false,
              fill: false,
              fillRatio: 100,
              style: {
                width: '100%',
                minHeight: '80px'
              }
            }
          },
          {
            name: 'el-divider',
            label: '分割线',
            icon: 'Remove',
            props: {
              direction: 'horizontal',
              contentPosition: 'center',
              borderStyle: 'solid'
            }
          }
        ]
      },
      {
        name: 'layout',
        label: '布局组件',
        components: [
          {
            name: 'el-header',
            label: '页头',
            icon: 'Menu',
            props: {
              height: '60px',
              style: {
                backgroundColor: '#f5f7fa',
                color: '#333',
                lineHeight: '60px',
                textAlign: 'center'
              }
            }
          },
          {
            name: 'el-footer',
            label: '页脚',
            icon: 'Menu',
            props: {
              height: '60px',
              style: {
                backgroundColor: '#f5f7fa',
                color: '#333',
                lineHeight: '60px',
                textAlign: 'center'
              }
            }
          },
          {
            name: 'el-aside',
            label: '侧边栏',
            icon: 'Operation',
            props: {
              width: '200px',
              style: {
                backgroundColor: '#f5f7fa',
                color: '#333',
                textAlign: 'center',
                lineHeight: '200px'
              }
            }
          },
          {
            name: 'el-main',
            label: '主要区域',
            icon: 'Document',
            props: {
              style: {
                backgroundColor: '#fff',
                color: '#333',
                textAlign: 'center',
                minHeight: '300px'
              }
            }
          }
        ]
      },
      {
        name: 'basic',
        label: '基础组件',
        components: [
          { 
            name: 'el-button', 
            label: '按钮', 
            icon: 'Plus',
            props: { type: 'primary', size: 'default' },
            slots: {
              default: '按钮'
            }
          },
          { 
            name: 'el-link', 
            label: '链接', 
            icon: 'Link',
            props: { type: 'primary', underline: true, text: '链接' } 
          },
          { 
            name: 'el-divider', 
            label: '分割线', 
            icon: 'Remove',
            props: { direction: 'horizontal', contentPosition: 'center' } 
          },
          { 
            name: 'el-icon', 
            label: '图标', 
            icon: 'Star',
            props: { color: '#409EFF', size: '20px' } 
          }
        ]
      },
      {
        name: 'form',
        label: '表单组件',
        components: [
          { 
            name: 'el-input', 
            label: '输入框', 
            icon: 'Edit',
            props: { placeholder: '请输入内容', clearable: true } 
          },
          { 
            name: 'el-select', 
            label: '选择器', 
            icon: 'Select',
            props: { placeholder: '请选择' } 
          },
          { 
            name: 'el-switch', 
            label: '开关', 
            icon: 'Switch',
            props: { activeText: '开启', inactiveText: '关闭' } 
          },
          { 
            name: 'el-checkbox', 
            label: '复选框', 
            icon: 'Check',
            props: { label: '选项' } 
          }
        ]
      },
      {
        name: 'data',
        label: '数据组件',
        components: [
          { 
            name: 'el-table', 
            label: '表格', 
            icon: 'Grid',
            props: { border: true, stripe: true } 
          },
          { 
            name: 'el-pagination', 
            label: '分页', 
            icon: 'Sort',
            props: { total: 100, pageSize: 10, currentPage: 1 } 
          },
          { 
            name: 'el-progress', 
            label: '进度条', 
            icon: 'Loading',
            props: { percentage: 50, textInside: true, striped: true } 
          },
          { 
            name: 'el-tag', 
            label: '标签', 
            icon: 'Collection',
            props: { type: 'success', effect: 'light', closable: false, text: '标签' } 
          }
        ]
      },
      {
        name: 'navigation',
        label: '导航组件',
        components: [
          { 
            name: 'el-menu', 
            label: '导航菜单', 
            icon: 'Menu',
            props: { mode: 'vertical', backgroundColor: '#545c64' } 
          },
          { 
            name: 'el-breadcrumb', 
            label: '面包屑', 
            icon: 'Goods',
            props: { separator: '/' } 
          },
          { 
            name: 'el-tabs', 
            label: '标签页', 
            icon: 'DocumentCopy',
            props: { type: 'card' } 
          },
          { 
            name: 'el-dropdown', 
            label: '下拉菜单', 
            icon: 'ArrowDown',
            props: { trigger: 'hover' } 
          }
        ]
      },
      {
        name: 'feedback',
        label: '反馈组件',
        components: [
          { 
            name: 'el-dialog', 
            label: '对话框', 
            icon: 'Warning',
            props: { title: '提示', visible: false, width: '50%' } 
          },
          { 
            name: 'el-notification', 
            label: '通知', 
            icon: 'BellFilled',
            props: { title: '通知标题', message: '这是一条通知消息' } 
          },
          { 
            name: 'el-message', 
            label: '消息提示', 
            icon: 'Bell',
            props: { message: '这是一条消息', type: 'success' } 
          },
          { 
            name: 'el-loading', 
            label: '加载', 
            icon: 'Loading',
            props: { text: '加载中...', fullscreen: false } 
          }
        ]
      }
    ])

    // 画布组件列表
    const canvasItems = ref([])
    const selectedItem = ref(null)
    
    // 画布状态
    const canvasState = reactive({
      items: canvasItems,
      selectedItem: selectedItem,
      transform: {
        x: 0,
        y: 0,
        scale: 1,
        rotation: 0
      },
      history: [],
      historyIndex: -1
    })

    // 画布拖拽处理
    let isDraggingCanvas = false
    let startX = 0
    let startY = 0
    let startTransform = { x: 0, y: 0 }

    const handleCanvasMouseDown = (e) => {
      // 检查是否点击在元素上
      const element = e.target.closest('.canvas-element')
      
      if (element) {
        // 处理元素选择
        const index = parseInt(element.dataset.index)
        
        // Shift键多选
        if (e.shiftKey) {
          if (freeTransformState.selectedItems.has(index)) {
            freeTransformState.selectedItems.delete(index)
          } else {
            freeTransformState.selectedItems.add(index)
          }
        } else {
          // 单选
          if (!freeTransformState.selectedItems.has(index)) {
            freeTransformState.selectedItems.clear()
            freeTransformState.selectedItems.add(index)
          }
        }
        
        // 开始拖动元素
        freeTransformState.isDragging = true
        freeTransformState.dragStartX = e.clientX
        freeTransformState.dragStartY = e.clientY
        
        // 保存初始位置
        freeTransformState.selectedItems.forEach(idx => {
          const item = canvasItems.value[idx]
          item.initialLeft = parseInt(item.props.style?.left) || 0
          item.initialTop = parseInt(item.props.style?.top) || 0
        })
      } 
      // 点击空白区域开始框选或画布拖动
      else if (e.target === e.currentTarget) {
        // 如果没有按下Shift键，清空选择
        if (!e.shiftKey) {
          freeTransformState.selectedItems.clear()
        }
        
        // 开始画布拖动
        isDraggingCanvas = true
        startX = e.clientX
        startY = e.clientY
        startTransform = { ...canvasState.transform }
        e.currentTarget.style.cursor = 'grabbing'
      }
    }

    const handleCanvasMouseMove = (e) => {
      // 处理元素拖动
      if (freeTransformState.isDragging && freeTransformState.selectedItems.size > 0) {
        const dx = e.clientX - freeTransformState.dragStartX
        const dy = e.clientY - freeTransformState.dragStartY
        
        // 计算考虑画布缩放后的实际移动距离
        const scaledDx = dx / canvasState.transform.scale
        const scaledDy = dy / canvasState.transform.scale
        
        // 更新所有选中元素的位置
        freeTransformState.selectedItems.forEach(idx => {
          const item = canvasItems.value[idx]
          
          // 计算新位置（考虑初始位置）
          let newLeft = (item.initialLeft || 0) + scaledDx
          let newTop = (item.initialTop || 0) + scaledDy
          
          // 吸附到网格
          if (freeTransformState.snapToGrid) {
            newLeft = Math.round(newLeft / freeTransformState.gridSize) * freeTransformState.gridSize
            newTop = Math.round(newTop / freeTransformState.gridSize) * freeTransformState.gridSize
          }
          
          // 更新元素位置
          if (!item.props.style) {
            item.props.style = {}
          }
          item.props.style.left = `${newLeft}px`
          item.props.style.top = `${newTop}px`
        })
        
        // 更新辅助线
        updateSnapLines()
      } 
      // 处理画布拖动
      else if (isDraggingCanvas) {
        const dx = e.clientX - startX
        const dy = e.clientY - startY
        canvasState.transform.x = startTransform.x + dx
        canvasState.transform.y = startTransform.y + dy
      }
    }

    const handleCanvasMouseUp = () => {
      if (freeTransformState.isDragging) {
        freeTransformState.isDragging = false
        freeTransformState.snapLines = [] // 清除参考线
      }
      
      if (isDraggingCanvas) {
        isDraggingCanvas = false
        document.querySelector('.canvas').style.cursor = 'default'
      }
      saveStateToHistory()
    }

    // 清除选择
    const clearSelection = () => {
      if (!freeTransformState.isDragging) {
        freeTransformState.selectedItems.clear()
      }
    }

    // 更新对齐参考线
    const updateSnapLines = () => {
      if (freeTransformState.selectedItems.size === 0) return
      
      const lines = []
      const selectedBounds = getSelectedElementsBounds()
      
      // 检查与其他元素的对齐
      canvasItems.value.forEach((item, index) => {
        if (!freeTransformState.selectedItems.has(index)) {
          const bounds = getElementBounds(index)
          
          // 检查水平对齐
          if (Math.abs(bounds.left - selectedBounds.left) < 5) lines.push({ type: 'vertical', position: bounds.left })
          if (Math.abs(bounds.right - selectedBounds.right) < 5) lines.push({ type: 'vertical', position: bounds.right })
          if (Math.abs(bounds.centerX - selectedBounds.centerX) < 5) lines.push({ type: 'vertical', position: bounds.centerX })
          
          // 检查垂直对齐
          if (Math.abs(bounds.top - selectedBounds.top) < 5) lines.push({ type: 'horizontal', position: bounds.top })
          if (Math.abs(bounds.bottom - selectedBounds.bottom) < 5) lines.push({ type: 'horizontal', position: bounds.bottom })
          if (Math.abs(bounds.centerY - selectedBounds.centerY) < 5) lines.push({ type: 'horizontal', position: bounds.centerY })
        }
      })
      
      freeTransformState.snapLines = lines
    }

    // 获取选中元素的整体边界
    const getSelectedElementsBounds = () => {
      let left = Infinity, top = Infinity, right = -Infinity, bottom = -Infinity
      
      freeTransformState.selectedItems.forEach(index => {
        const bounds = getElementBounds(index)
        left = Math.min(left, bounds.left)
        top = Math.min(top, bounds.top)
        right = Math.max(right, bounds.right)
        bottom = Math.max(bottom, bounds.bottom)
      })
      
      return {
        left, top, right, bottom,
        width: right - left,
        height: bottom - top,
        centerX: (left + right) / 2,
        centerY: (top + bottom) / 2
      }
    }

    // 获取单个元素的边界
    const getElementBounds = (index) => {
      const item = canvasItems.value[index]
      const left = parseInt(item.props.style?.left) || 0
      const top = parseInt(item.props.style?.top) || 0
      const width = parseInt(item.props.style?.width) || 100
      const height = parseInt(item.props.style?.height) || 50
      
      return {
        left, top,
        right: left + width,
        bottom: top + height,
        width, height,
        centerX: left + width / 2,
        centerY: top + height / 2
      }
    }

    // 画布缩放
    const handleCanvasWheel = (e) => {
      e.preventDefault()
      const delta = e.deltaY > 0 ? -0.1 : 0.1
      zoomCanvas(delta)
    }

    const zoomCanvas = (delta) => {
      const scale = canvasState.transform.scale + delta
      canvasState.transform.scale = Math.max(0.5, Math.min(2, scale))
      saveStateToHistory()
    }

    // 画布重置
    const resetCanvas = () => {
      canvasState.transform = { x: 0, y: 0, scale: 1, rotation: 0 }
      saveStateToHistory()
    }

    const newArrayItem = ref('') // 用于数组属性添加新项
    let draggedComponent = null

    // 保存当前状态到历史记录
    const saveStateToHistory = () => {
      // 如果当前不是最新的历史记录，则截断后面的记录
      if (canvasState.historyIndex < canvasState.history.length - 1) {
        canvasState.history = canvasState.history.slice(0, canvasState.historyIndex + 1)
      }
      
      // 深度克隆当前完整状态
      const newState = {
        items: JSON.parse(JSON.stringify(canvasItems.value)),
        selectedItem: selectedItem.value ? JSON.parse(JSON.stringify(selectedItem.value)) : null,
        transform: JSON.parse(JSON.stringify(canvasState.transform))
      }
      
      // 添加新状态
      canvasState.history.push(newState)
      
      // 限制历史记录数量(最多50步)
      if (canvasState.history.length > 50) {
        canvasState.history.shift()
      } else {
        canvasState.historyIndex = canvasState.history.length - 1
      }
      
      console.log('State saved to history:', newState)
    }

    // 撤销操作
    const undo = () => {
      if (canvasState.historyIndex > 0) {
        canvasState.historyIndex--
        const state = canvasState.history[canvasState.historyIndex]
        canvasItems.value = JSON.parse(JSON.stringify(state.items))
        selectedItem.value = state.selectedItem ? JSON.parse(JSON.stringify(state.selectedItem)) : null
        canvasState.transform = JSON.parse(JSON.stringify(state.transform))
        console.log('Undo to state:', state)
      }
    }

    // 重做操作
    const redo = () => {
      if (canvasState.historyIndex < canvasState.history.length - 1) {
        canvasState.historyIndex++
        const state = canvasState.history[canvasState.historyIndex]
        canvasItems.value = JSON.parse(JSON.stringify(state.items))
        selectedItem.value = state.selectedItem ? JSON.parse(JSON.stringify(state.selectedItem)) : null
        canvasState.transform = JSON.parse(JSON.stringify(state.transform))
        console.log('Redo to state:', state)
      }
    }

    // 监听所有状态变更，自动保存历史记录
    watch([canvasItems, selectedItem], () => {
      saveStateToHistory()
    }, { deep: true })

    watch(() => canvasState.transform, () => {
      saveStateToHistory()
    }, { deep: true })

    // 键盘快捷键支持
    const handleKeyDown = (e) => {
      if (e.ctrlKey || e.metaKey) {
        if (e.key === 'z') {
          e.preventDefault()
          undo()
        } else if (e.key === 'y') {
          e.preventDefault()
          redo()
        }
      }
    }

    onMounted(() => {
      window.addEventListener('keydown', handleKeyDown)
      saveStateToHistory()
    })

    onBeforeUnmount(() => {
      window.removeEventListener('keydown', handleKeyDown)
    })

    const dragStart = (event, comp) => {
      draggedComponent = comp
      event.dataTransfer.effectAllowed = 'copy'
      // 设置拖放数据
      event.dataTransfer.setData('application/json', JSON.stringify({
        component: comp.name,
        props: comp.props
      }))
    }

    const drop = (event) => {
      event.preventDefault()
      if (draggedComponent) {
        // 计算考虑画布变换后的实际位置
        const rect = event.currentTarget.getBoundingClientRect()
        const x = (event.clientX - rect.left - canvasState.transform.x) / canvasState.transform.scale
        const y = (event.clientY - rect.top - canvasState.transform.y) / canvasState.transform.scale
        
        // 将kebab-case转换为PascalCase (el-button -> ElButton)
        const componentName = draggedComponent.name
          .split('-')
          .map(word => word.charAt(0).toUpperCase() + word.slice(1))
          .join('')
          .replace('El', 'El') // 确保El前缀正确
        
        // 处理特殊的props，确保文本内容正确显示
        const props = { 
          ...draggedComponent.props,
          style: {
            ...draggedComponent.props.style,
            // 容器组件(el-row/el-col)不需要绝对定位
            ...(draggedComponent.name.includes('el-row') || draggedComponent.name.includes('el-col') ? {} : {
              position: 'absolute',
              left: `${x}px`,
              top: `${y}px`
            })
          }
        }
        
        // 添加组件到画板
        canvasItems.value.push({
          component: componentName,
          props: props,
          children: [] // 初始化子组件数组
        })
        
        // 自动选中新添加的组件
        selectItem(canvasItems.value.length - 1)
        saveStateToHistory()
      }
    }

    // 更新嵌套组件
    const updateChildren = (parentIndex, newChildren) => {
      if (canvasItems.value[parentIndex]) {
        canvasItems.value[parentIndex].children = newChildren
        saveStateToHistory()
      }
    }

    // 选择嵌套组件
    const selectNestedItem = (parentIndex, childIndex) => {
      selectedItem.value = {
        type: 'nested',
        parentIndex,
        childIndex
      }
    }

    // 处理子组件选择事件
    const onChildSelected = (parentIndex, childIndex) => {
      selectedItem.value = {
        parentIndex,
        childIndex
      }
    }

    const selectItem = (index) => {
      // 如果是普通组件，直接选中
      if (typeof index === 'number') {
        selectedItem.value = index
      } 
      // 如果是嵌套组件，保存嵌套路径
      else if (typeof index === 'object' && index !== null) {
        selectedItem.value = index
      }
      saveStateToHistory()
    }

    // 获取基础属性（排除style对象）
    const getBasicProps = (props) => {
      const result = {};
      for (const key in props) {
        if (key !== 'style') {
          result[key] = props[key];
        }
      }
      return result;
    }

    // 获取样式属性的计算属性
    const getStyleProp = (itemIndex, styleProp) => {
      return computed({
        get: () => {
          if (typeof itemIndex === 'number') {
            if (!canvasItems.value[itemIndex].props.style) {
              canvasItems.value[itemIndex].props.style = {};
            }
            return canvasItems.value[itemIndex].props.style[styleProp];
          } else if (itemIndex && itemIndex.type === 'nested') {
            const { parentIndex, childIndex } = itemIndex;
            if (!canvasItems.value[parentIndex].children[childIndex].props.style) {
              canvasItems.value[parentIndex].children[childIndex].props.style = {};
            }
            return canvasItems.value[parentIndex].children[childIndex].props.style[styleProp];
          }
          return '';
        },
        set: (value) => {
          if (typeof itemIndex === 'number') {
            if (!canvasItems.value[itemIndex].props.style) {
              canvasItems.value[itemIndex].props.style = {};
            }
            canvasItems.value[itemIndex].props.style[styleProp] = value;
          } else if (itemIndex && itemIndex.type === 'nested') {
            const { parentIndex, childIndex } = itemIndex;
            if (!canvasItems.value[parentIndex].children[childIndex].props.style) {
              canvasItems.value[parentIndex].children[childIndex].props.style = {};
            }
            canvasItems.value[parentIndex].children[childIndex].props.style[styleProp] = value;
          }
        }
      });
    }

    // 判断是否为颜色属性
    const isColorProp = (propKey) => {
      return propKey.toLowerCase().includes('color') || 
             propKey.toLowerCase().includes('background');
    }

    // 判断是否为选择属性
    const isSelectProp = (propKey) => {
      return ['type', 'size', 'effect', 'placement', 'direction', 
              'trigger', 'mode', 'position', 'align', 'justify'].includes(propKey);
    }

    // 获取属性的显示标签
    const getPropLabel = (propKey) => {
      // 将驼峰命名转换为空格分隔的单词
      return propKey.replace(/([A-Z])/g, ' $1')
        .replace(/^./, (str) => str.toUpperCase());
    }

    // 获取选择属性的选项
    const getSelectOptions = (propKey, componentName) => {
      const commonOptions = {
        type: [
          { label: '默认', value: '' },
          { label: '主要', value: 'primary' },
          { label: '成功', value: 'success' },
          { label: '警告', value: 'warning' },
          { label: '危险', value: 'danger' },
          { label: '信息', value: 'info' }
        ],
        size: [
          { label: '默认', value: 'default' },
          { label: '大', value: 'large' },
          { label: '小', value: 'small' }
        ],
        direction: [
          { label: '水平', value: 'horizontal' },
          { label: '垂直', value: 'vertical' }
        ],
        position: [
          { label: '左', value: 'left' },
          { label: '右', value: 'right' },
          { label: '上', value: 'top' },
          { label: '下', value: 'bottom' }
        ],
        justify: [
          { label: '起始', value: 'start' },
          { label: '结束', value: 'end' },
          { label: '居中', value: 'center' },
          { label: '两端对齐', value: 'space-between' },
          { label: '环绕对齐', value: 'space-around' },
          { label: '均匀对齐', value: 'space-evenly' }
        ],
        align: [
          { label: '顶部', value: 'top' },
          { label: '中间', value: 'middle' },
          { label: '底部', value: 'bottom' }
        ]
      };
      
      return commonOptions[propKey] || [];
    }

    // 添加数组项
    const addArrayItem = (itemIndex, propKey) => {
      if (newArrayItem.value.trim() === '') return;
      
      if (typeof itemIndex === 'number') {
        if (!Array.isArray(canvasItems.value[itemIndex].props[propKey])) {
          canvasItems.value[itemIndex].props[propKey] = [];
        }
        canvasItems.value[itemIndex].props[propKey].push(newArrayItem.value);
      } else if (itemIndex && itemIndex.type === 'nested') {
        const { parentIndex, childIndex } = itemIndex;
        if (!Array.isArray(canvasItems.value[parentIndex].children[childIndex].props[propKey])) {
          canvasItems.value[parentIndex].children[childIndex].props[propKey] = [];
        }
        canvasItems.value[parentIndex].children[childIndex].props[propKey].push(newArrayItem.value);
      }
      
      newArrayItem.value = '';
      saveStateToHistory();
    }

    // 移除数组项
    const removeArrayItem = (itemIndex, propKey, index) => {
      if (typeof itemIndex === 'number') {
        canvasItems.value[itemIndex].props[propKey].splice(index, 1);
      } else if (itemIndex && itemIndex.type === 'nested') {
        const { parentIndex, childIndex } = itemIndex;
        canvasItems.value[parentIndex].children[childIndex].props[propKey].splice(index, 1);
      }
    }

    return {
      componentCategories,
      activeCategories,
      canvasItems,
      selectedItem,
      dragStart,
      drop,
      selectItem,
      updateChildren,
      selectNestedItem,
      onChildSelected,
      // 新增的方法和数据
      newArrayItem,
      getBasicProps,
      getStyleProp,
      isColorProp,
      isSelectProp,
      getPropLabel,
      getSelectOptions,
      addArrayItem,
      removeArrayItem,
      canvasState,
      handleCanvasMouseDown,
      handleCanvasMouseMove,
      handleCanvasMouseUp,
      handleCanvasWheel,
      zoomCanvas,
      resetCanvas,
      undo,
      redo
    }
  }
})
</script>

<style scoped>
.designer-container {
  display: flex;
  height: 100vh;
  width: 100vw;
  background-color: #f5f7fa;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.toolbox, .property-panel {
  width: 280px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  z-index: 10;
}

.canvas {
  flex: 1;
  padding: 20px;
  margin: 0 15px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

.canvas-controls {
  position: sticky;
  top: 0;
  background: white;
  padding: 10px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.zoom-level {
  margin-left: 10px;
  font-size: 14px;
  color: #666;
}

.canvas-content {
  min-height: calc(100vh - 100px);
  border: 1px dashed #ccc;
  border-radius: 4px;
  padding: 20px;
  position: relative;
  background-image: 
    linear-gradient(#e5e5e5 1px, transparent 1px),
    linear-gradient(90deg, #e5e5e5 1px, transparent 1px);
  background-size: 20px 20px;
  background-position: center;
}

.empty-canvas {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #909399;
  font-size: 14px;
}

h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.component-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-top: 10px;
}

.component-item {
  cursor: move;
  text-align: center;
}

.component-label {
  font-size: 12px;
  margin-bottom: 5px;
}

.component-icon {
  font-size: 20px;
  color: #409eff;
}

/* 自定义折叠面板样式 */
:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  font-weight: 500;
  color: #303133;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 0 10px;
}

:deep(.el-collapse-item__content) {
  padding: 10px 0;
}
</style>